<template>
	<view class="fill-width-height">

		<view class="fill-width-height flex-col">
			<view class="fill-width" style="padding: 10px 0px;" id="backgroundImg">
				<view class="fill-width flex-row align-center justify-center" style="gap:16px;padding: 16px 0;">
					<uv-button type="primary" text="选择上传您的二维码" @click="selectQRImg"></uv-button>
					<!-- <uv-button type="success" text="选择表情图" @click="selectMote" v-show="isShowMote"></uv-button> -->
				</view>

				<movable-area data-index="5" class="A" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
					@touchend="handleTouchEnd" data-bgColor="#ffffff" data-type="view">
					<view data-index="4" ref="saveview" id="saveview" class="container" data-type="view">
						<movable-view :style="getMovableStyle" class="F-F" direction="all" data-index="11">
							<image :src="getImgUrl(false)" :data-src="getImgUrl(false)" mode="widthFix"
								class="image drawInfo qr_image" data-type="img" data-index="30"/>
						</movable-view>
						<image :src="backGroundImgUrl" :data-src="backGroundImgUrl" mode="widthFix" data-index="40"
							style="width: 70%;margin: 0 auto;" alt=""
							class="drawInfo" data-type="img" />
					</view>
				</movable-area>
			</view>

			<!-- <uv-image src="imageSrc"></uv-image> -->

			<view class="flex-row justify-center align-center" style="gap: 5px;margin-top: 10px;">
				
				<Adver ref="adverRef" @adCompleted="adCompletedAhareImg">
					<uv-button 
						type="primary"
						text="分享到" 
					>
					</uv-button>
				</Adver>
				
				<Adver ref="saveAdverRef" @adCompleted="adCompletedAaveImg">
					<uv-button 
						type="success" 
						text="保存到相册"
						v-show="isShowMote"
					 >
					</uv-button>
				</Adver>
				
			</view>
			
			<view class="flex-col align-center justify-center" style="padding: 10px;">
				<text>1. 上传二维码 </text>
				<text>2. 拖动二维码位置,二指捏调整二维码大小 </text>
				<text>3. 分享或保存 </text>
			</view>
		</view>

		<tkview2img :saveId="saveId" @resFilePath="resFilePath"></tkview2img>
	</view>
</template>


<script>
	import sharePages from '@/framework/plugins/sharePages'
	import tkview2img from '@/components/tk-view2img/tk-view2img'
	import Adver from '@/framework/componentsUI/adver/index.vue'
	import {
		getQrImg
	} from '@/api/imgTools'
	export default {
		mixins: [sharePages],
		components: {
			tkview2img,
			Adver
		},
		data() {
			return {
				saveType: '',
				saveId: '',
				imageSrc: '',
				backGroundImgUrl: '',
				isShowMote: true,
				fileId: '',
				x: 0,
				y: 0,
				old: {
					x: 0,
					y: 0
				},
				zhiwidth: 100, //Movable-view的初始宽度
				zhiheight: 100, //Movable-view的初始高度
				zhi: 1, //Movable-view的初始缩放比例
				zuixiaozhi: 0.5, //最小缩放比例
				zuidazhi: 2, //最大缩放比例
				startDistance: 0, //双指触摸起始距离
				currentDistance: 0, //双指触摸当前距离
			}
		},
		computed: {
			backGroundStyle() {
				return {
					backgroundImage: `url(${this.backGroundImgUrl})`
				}
			},
			getMovableStyle() {
				return {
					width: this.zhiwidth * this.zhi + 'px',
					height: this.zhiheight * this.zhi + 'px',
					transform: `scale(${this.zhi}, ${this.zhi})`,
					'transform-origin': 'center center'
				}
			}
		},
		methods: {
			handleTouchStart(event) {
				if (event.touches.length === 2) { //判断是否为双指触摸
					const x1 = event.touches[0].clientX;
					const y1 = event.touches[0].clientY;
					const x2 = event.touches[1].clientX;
					const y2 = event.touches[1].clientY;
					const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); //计算两指间距
					console.log("A", distance)
					this.startDistance = distance;
				}
			},
			handleTouchMove(event) {
				if (event.touches.length === 2) { //判断是否为双指触摸
					const x1 = event.touches[0].clientX;
					const y1 = event.touches[0].clientY;
					const x2 = event.touches[1].clientX;
					const y2 = event.touches[1].clientY;
					const distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2); //计算两指间距
					const scale = distance / this.startDistance; //计算缩放比例
					this.zhi = this.zhi * scale; //更新缩放比例
					console.log("B", this.zhi)
					if (this.zhi < this.zuixiaozhi) { //限制最小缩放比例
						this.zhi = this.zuixiaozhi;
					}
					if (this.zhi > this.zuidazhi) { //限制最大缩放比例
						this.zhi = this.zuidazhi;
					}
					this.startDistance = distance; //更新起始距离为当前距离
				}
			},
			handleTouchEnd() { //触摸结束时重置起始距离为0
				this.startDistance = 0;
			},
			tap: function(e) {
				this.x = this.old.x
				this.y = this.old.y
				this.$nextTick(function() {
					this.x = 30
					this.y = 30
				})
			},
			onChange: function(e) {
				this.old.x = e.detail.x
				this.old.y = e.detail.y
			},
			fangda() {
				let zhii = this.zhi += 0.5;
				let width = this.zhiwidth += 50
				let height = this.zhiheight += 50
				this.zhiwidth = width
				this.zhiheight = height
				if (zhii < 0.5) {
					uni.showModal({
						title: "低于0.5倍了",
						icon: null
					})
				} else if (zhii > 2) {
					uni.showModal({
						title: "太大了",
						icon: null
					})
				}
				if (zhii = 0) {
					this.zhiwidth = width + 50
					this.zhiheight = height + 50
				}
			},
			suoxiao() {
				let zhii = this.zhi -= 0.5;
				let width = this.zhiwidth -= 50
				let height = this.zhiheight -= 50
				this.zhiwidth = width
				this.zhiheight = height

				if (zhii < 0.5) {
					uni.showModal({
						title: "低于0.5倍了",
						icon: null
					})
				} else if (zhii > 2) {
					uni.showModal({
						title: "太大了",
						icon: null
					})
				}
			},
			getImgUrl(isDown = false) {
				if (this.fileId?.length <= 0) {
					return
				}
				if(this?.fileId?.startsWith('http')){
					return this.fileId
				}
				const path = isDown ? 'down' : 'preview'
				return this.$config.replacehUrl(`imgStore/imageTool/${path}?tempId=${this.fileId}`, true)
			},
			selectQRImg() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.imagePath = res.tempFilePaths[0];
						uni.uploadFile({
							url: 'imgStore/imageTool/getQrImg',
							filePath: this.imagePath,
							name: 'file',
							formData: {
								user: 'test'
							},
							success: (res) => {
								if (res?.data?.code == 200) {
									this.fileId = res.data.msg
								} else {
									this.fileId = ''
									uni.showModal({
										title: res.data.msg,
										icon: null
									})
								}
							}
						})
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
					}
				});
			},
			selectMote() {},
			adCompletedAhareImg() {
				this.saveType = 'share'
				this.saveId = this.generateUUID()
			},
			adCompletedAaveImg() {
				this.saveType = 'save'
				this.saveId = this.generateUUID()
			},
			resFilePath(tempFilePath){
				if(this.saveType === 'share'){
					wx.showShareImageMenu({
						path: tempFilePath
					})
				} else if(this.saveType === 'save'){
					this.saveImageToAlbum(tempFilePath)
				}
			},
			saveImageToAlbum(filePath) {
				uni.saveImageToPhotosAlbum({
					filePath: filePath,
					success: () => {
						uni.showToast({
							title: '图片保存成功',
							icon: 'success',
						});
					},
					fail: (err) => {
						console.error('保存图片失败:', err);
						uni.showToast({
							title: '保存图片失败，请检查权限',
							icon: 'none',
						});
					},
				});
			},
			generateUUID() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			}
		},
		onLoad({
			imgUrl
		}) {
			let decodeImgUrl = decodeURIComponent(imgUrl)
			this.backGroundImgUrl = decodeImgUrl
		}
	}
</script>

<style scoped>
	.A {
		width: 100%;
		height: auto;
		/* background-color: coral; */
	}

	.F-F {
		/* background-color: #5555ff; */
		justify-content: center;
		align-items: center;
		display: flex;
		color: #ffffff;
		font-size: 10rpx;
		border: 1px solid #ffffff;
		z-index: 300;
	}

	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
	}

	.image {
		width: 100%;
		height: auto;
	}
	.qr_image{
		/* padding: 2px; */
	}
</style>